package com.liukh.obwiki.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; // 添加这个导入
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 拦截器：Spring框架特有的，常用于登录校验，权限校验，请求日志打印 /login
 */
@Component
public class Durationinterceptor  implements HandlerInterceptor { // 修复类名大小写

    private static final Logger LOG = LoggerFactory.getLogger(Durationinterceptor .class); // 类名同步修改

    // 执行控制层方法之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 打印请求信息
        LOG.info("------------- DurationInterceptor 开始 -------------");
        LOG.info("请求地址: {} {}", request.getRequestURL().toString(), request.getMethod());
        LOG.info("远程地址: {}", request.getRemoteAddr());

        long startTime = System.currentTimeMillis();
        request.setAttribute("requestStartTime", startTime);
        return true;
    }

    // 执行控制层方法之后执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long startTime = (Long) request.getAttribute("requestStartTime");
        long duration = System.currentTimeMillis() - startTime;

        LOG.info("------------- DurationInterceptor 结束 耗时：{} ms -------------", duration);
    }

    // 添加 afterCompletion 方法用于异常情况
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if (ex != null) {
            long startTime = (Long) request.getAttribute("requestStartTime");
            long duration = System.currentTimeMillis() - startTime;
            LOG.error("请求处理异常! 耗时：{} ms, 异常信息: {}", duration, ex.getMessage());
        }
    }
}